import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'

const state = {
  token: getToken(),
  name: '',
  avatar: '',
  showSchema: ''
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_SHOWSCHEMA: (state, showSchema) => {
    state.showSchema = showSchema
  }
}

const actions = {
  // user login
  login({ commit }, requestData) {
    // const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login(requestData)
        .then((data) => {
          console.log(data)
          commit('SET_TOKEN', data.token)
          setToken(data.token)
          resolve()
        })
        .catch((error) => {
          reject(error)
        })
    })
  },

  // 设置用户头像
  setImg({ commit }, img) {
    commit('SET_AVATAR', img)
  },

  // get user info
  getInfo({ commit, state }) {
    getInfo()
    .then((data) => {
      const { userName, img, showSchema } = data
      commit('SET_NAME', userName)
      commit('SET_AVATAR', img)
      commit('SET_SHOWSCHEMA', showSchema)

    })
    .catch((error) => {
      // 
      commit('SET_SHOWSCHEMA', 'list')

    })
  },

  // user logout
  // logout({ commit, state, dispatch }) {
  //   return new Promise((resolve, reject) => {
  //     logout(state.token)
  //       .then(() => {
  //         commit('SET_TOKEN', '')
  //         commit('SET_ROLES', [])
  //         removeToken()

  //         // reset visited views and cached views
  //         // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
  //         dispatch('tagsView/delAllViews', null, { root: true })

  //         resolve()
  //       })
  //       .catch((error) => {
  //         reject(error)
  //       })
  //   })
  // },

  // remove token
  resetToken({ commit }) {
    return new Promise((resolve) => {
      commit('SET_TOKEN', '')
      removeToken()
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
